<template>
  <div class="login-container flex flex-center align-center">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form bg-white relative flex flex-start" autocomplete="on" label-position="left">
      <div class="login_left">
        <img src="@/assets/home_images/login-left-img.png" />
        <div>版本号</div>
        <div>v2.0.0</div>
      </div>
      <div class="login_right padding_15 flex flex-center align-center">
        <div>
          <h3 class="login_title font-weight--lg">登录</h3>
          <el-form-item prop="username">
            <el-input ref="usernameRef" v-model.trim="loginForm.username" placeholder="请输入用户名" name="username" type="text" tabindex="1" autocomplete="on">
              <i slot="prefix" class="svg-container">
                <svg-icon icon-class="user" />
              </i>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input ref="passwordRef" v-model="loginForm.password" :type="isPasswordType ? 'password' : 'text'" placeholder="请输入密码" name="password" tabindex="2" autocomplete="on" @keyup.native="checkCapslock" @blur="capsTooltip = false" @keyup.enter.native="handleLogin">
              <i slot="prefix" class="svg-container">
                <svg-icon icon-class="password" />
              </i>
            </el-input>
            <span class="password_icon pointer absolute font-size--xs" @click="changePasswordType">
              <svg-icon :icon-class="isPasswordType ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>

          <!-- <el-form-item prop="proId">
            <el-select class="full-width" v-model="loginForm.proId" placeholder="请选择用户渠道">
              <el-option :label="item.name" :value="item.value" v-for="item in userChannel" :key="'channel' + item.value"></el-option>
            </el-select>
          </el-form-item> -->

          <el-button :loading="loading" type="primary" class="login_btn full-width" @click.native.prevent="handleLogin">登录</el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { setLoginToken } from '@/utils/Token';
import { Login, GetCurrentUserRouters } from '@/api/PublicServices';
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入正确的用户名!'));
      } else {
        callback();
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能少于6位!'));
      } else {
        callback();
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        proId: 4
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      isPasswordType: true,
      capsTooltip: false,
      loading: false,
      redirect: null,
      otherQuery: null,
      userChannel: [
        { name: '3D云镜', value: 1 },
        { name: '洗衣先生', value: 2 },
        { name: '微服务', value: 4 },
        { name: '三翼鸟', value: 5 },
        { name: '洗衣机营销', value: 6 }
      ]
    }
  },
  created() {
    const query = this.$route.query;
    if (query) {
      this.redirect = query.redirect || '/home';
      this.otherQuery = this.getOtherQuery(query);
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.usernameRef.focus();
    } else if (this.loginForm.password === '') {
      this.$refs.passwordRef.focus();
    }
  },
  methods: {
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z';
    },
    changePasswordType() {
      this.isPasswordType = !this.isPasswordType;
      this.$nextTick(() => {
        this.$refs.passwordRef.focus();
      })
    },
    handleLogin() {
      this.$refs.loginFormRef.validate(valid => {
        if (valid) {
          this.loading = true;
          Login({
            username: this.loginForm.username.trim(),
            password: this.loginForm.password,
            authType: 'sys',
            proId: this.loginForm.proId
          })
          .then(data => {
            if (data.code == 200) {
              this.$store.dispatch('user/login', {
                authorization: 'Bearer' + data.data.authorization,
                user: JSON.stringify(data.data.user)
              });
              setLoginToken('Bearer' + data.data.authorization, JSON.stringify(data.data.user), moment().add(data.data.expire, 'seconds').format('YYYY-MM-DD HH:mm:ss'));

              this.$store.commit('user/SET_BTNS', data.data.user.permissions);

              // 让用户选择登录账号得用户类型
              if (data.data.user.userType == 3) {
                if (data.data.user.isMch == 1 && data.data.user.isStore == 1) {
                  this.$confirm('检测到您的账户存在多个角色，请选择您的角色!', '提示', {
                    confirmButtonText: '商户',
                    cancelButtonText: '店铺',
                    showClose: false,
                    closeOnClickModal: false,
                    closeOnPressEscape: false
                  })
                  .then(() => {
                    this.getCurrentUserCheckRoleRouters(1);
                    this.$store.commit('user/SET_USERROLE', 1);
                  })
                  .catch(() => {
                    this.getCurrentUserCheckRoleRouters(2);
                    this.$store.commit('user/SET_USERROLE', 2);
                  });
                } else if (data.data.user.isMch == 1 && data.data.user.isStore == 0) {
                  this.getCurrentUserCheckRoleRouters(1);
                  this.$store.commit('user/SET_USERROLE', 1);
                }  else if (data.data.user.isMch == 0 && data.data.user.isStore == 1) {
                  this.getCurrentUserCheckRoleRouters(2);
                  this.$store.commit('user/SET_USERROLE', 2);
                }
              } else if (data.data.user.userType == 1) { //新增了商户类型的判断
                this.getCurrentUserCheckRoleRouters(1);
                this.$store.commit('user/SET_USERROLE', 1);
              } else {
                this.getCurrentUserCheckRoleRouters(0);
                this.$store.commit('user/SET_USERROLE', 0);
              }
            } else {
              this.loading = false;
              this.$message.error('登录失败!');
            }
          })
          .catch(() => {
            this.loading = false;
          })
        }
      })
    },
    // 通过用户的选择进行响应的路由菜单获取
    getCurrentUserCheckRoleRouters(type) {
      // 对比之前在的缓存模块
      GetCurrentUserRouters({ type: type })
      .then(currentRouter => {
        if (currentRouter.code == 200) {
          if (!currentRouter.data || !currentRouter.data.length) {
            this.loading = false;
            this.$message.error('该账号未配置菜单，请联系管理员配置!');
            return;
          }
          let allHasRoutes = [];
          currentRouter.data.forEach(item => {
            allHasRoutes = allHasRoutes.concat(this.renderDeep(item.children));
          })
          // 缓存下来所有的路由模块数据
          localStorage.setItem('CurrentUserRoutesModule', JSON.stringify(allHasRoutes));
          this.$store.commit('user/SET_ROUTES', allHasRoutes);
          console.log(allHasRoutes)
          console.log( this.deepFind(allHasRoutes[0]))
          // 跳转到第一个路由的path
          this.$router.push({
            path: this.deepFind(allHasRoutes[0])
          })
          return;
          // 设置缓存
          sessionStorage.setItem('CurrentModule', JSON.stringify(currentRouter.data));
          // 读取注销登录前所在的模块
          const CurrentModule = sessionStorage.getItem('CurrentModule');
          if (CurrentModule) {
            const finder = currentRouter.data.find(item => {
              if (JSON.parse(CurrentModule).name == item.name && JSON.parse(CurrentModule).path == item.path && JSON.parse(CurrentModule).type == item.type) {
                return item;
              }
            })
            // 返回需要跳转到的模块，如果没有那个模块就跳首页
            if (finder) {
              this.$store.commit('user/SET_ROUTES', this.renderDeep(finder.children));
              // 是否有原来需要跳转页面的权限，没有跳第一个菜单
              const needAddRoutes = this.renderDeep(finder.children);
              if (JSON.stringify(needAddRoutes).indexOf(this.redirect) >= 0) {
                this.loading = false;
                this.$message.success('登录成功!');
                this.$router.replace({
                  path: this.redirect || '/home',
                  query: this.otherQuery
                });
              } else {
                this.loading = false;
                this.$message.success('登录成功!');
                this.$router.replace({
                  path: (needAddRoutes[0] && needAddRoutes[0].children[0] && needAddRoutes[0].children[0].path) ? needAddRoutes[0].children[0].path : '/home'
                });
              }
              return;
            }
          }
        }
        this.loading = false;
        this.$message.success('登录成功!');
        this.$router.replace({
          path: '/home'
        });
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur];
        }
        return acc;
      }, {})
    },
    deepFind(value) {
        if (value.children && value.children.length) {
            if(value.children[0].children && value.children[0].children.length){
                 return this.deepFind(value.children[0]);
            }
            return value.children[0].path
        } else {
           if (value.path) {
            return value.path
           }
          this.$message.info('请联系开发进行配置!');
          return '';
        }
    },
    // 深层树形结构生成
    renderDeep(value) {
      if (!value || !value.length) {
        return [];
      }
      return value.map(item => {
        return {
          path: item.path ? item.path : '',
          name: item.meta.title ? item.meta.title : '',
          component: '',
          hidden: item.hidden,
          redirect: item.redirect ? item.redirect : '',
          meta: {
            title: item.name ? item.name : '',
            icon: item.meta.icon ? item.meta.icon : '',
            activeMenu: item.meta.activeMenu ? item.meta.activeMenu : ''
          },
          children: this.renderDeep(item.children)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;

.login-container {
  min-height: 100%;
  width: 100%;
  min-width: 1080px;
  background: url('../../assets/home_images/bg-home-bg.png');
  background-size: cover;

  .login-form {
    width: 720px;
    height: 400px;
    min-width: 720px;
    max-width: 100%;
    overflow: hidden;
    border-radius: 10px;
    box-shadow: 0 0 15px rgba(255, 255, 255, 0.8);

    .login_left {
      min-width: 260px;
      max-width: 300px;
      flex: 0 0 260px;
      text-align: center;
      color: #23254e;
      background-color: #f0f2f5;
    }

    .login_right {
      flex: 1;

      > div {
        width: 90%;
        min-width: 360px;
        max-width: 420px;
      }

      .login_title {
        font-size: 26px;
        margin: 0px auto 40px auto;
        text-align: center;
        color: #23254e;
      }

      .password_icon {
        right: 10px;
        top: 3px;
        color: $dark_gray;
        user-select: none;
      }
    }
  }

  .svg-container {
    color: $dark_gray;
  }

  .login_btn {
    margin-bottom: 30px;
  }
}
</style>
